import type * as ts from 'typescript'
import { createFilter } from '@rollup/pluginutils'

const txtFilter = createFilter(['**/*.txt'])

export default function init(modules: { typescript: typeof ts }) {
  const ts = modules.typescript

  return {
    create(info: ts.server.PluginCreateInfo) {
      const proxy: ts.LanguageService = Object.create(null)

      proxy.getQuickInfoAtPosition = (fileName, position) => {
        if (!txtFilter(fileName))
          return info.languageService.getQuickInfoAtPosition(fileName, position)

        const content = ts.sys.readFile(fileName, 'utf8') ?? ''
        const literalType = JSON.stringify(content.trimEnd())
        return {
          kind: ts.ScriptElementKind.string,
          kindModifiers: '',
          textSpan: { start: 0, length: content.length },
          displayParts: [
            { kind: 'text', text: `literal type: ${literalType}` }
          ]
        } as ts.QuickInfo
      }

      return proxy
    }
  }
}